<?php

namespace App\Admin\Controllers;

use App\Models\Type;
use App\Models\Video;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;

class VideosController extends AdminController
{
    public function index(Content $content): Content
    {
        return $content
            ->header('列表')
            ->description('全部')
            ->breadcrumb(['text' => '列表', 'url' => ''])
            ->body($this->grid());
    }

    protected function grid(): Grid
    {
        return Grid::make(Video::with(['types']), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('types', '所属分类')->display(function ($types) {
                return $types->pluck('name')->implode(',');
            })->label('pink');
            $grid->column('title')->label();
            $grid->column('cover')->image('', 50);
            $grid->column('url')->link();
            $grid->column('created_at');

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
                $filter->like('title');
                $filter->equal('types.id', '所属分类')->select(Type::all()->pluck('name', 'id'));
            });
        });
    }

    protected function form(): Form
    {
        return Form::make(Video::with(['types']), function (Form $form) {
            $form->display('id');
            $form->checkbox('types', '所属分类')->customFormat(function ($v) {
                if (!$v) return [];

                // 这一步非常重要，需要把数据库中查出来的二维数组转化成一维数组
                return array_column($v, 'id');
            })->options(Type::all()->pluck('name', 'id')->toArray());

            $form->text('title')->required();
            $form->image('cover')
                ->autoUpload()->uniqueName()->saveFullUrl()->removable(false)
                ->chunkSize(1000)->maxSize(10024000)->threads(10)
                ->rules('required', ['required' => '请上传视频封面'])
                ->setLabelClass(['asterisk']);
            $form->url('url')->required();

            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}
